package com.example.android.commitcontent.ime.dict;

import android.content.Context;
import android.text.TextUtils;

import com.example.android.commitcontent.ime.beans.HanZiCharacter;
import com.example.android.commitcontent.ime.cores.utils.LogHelper;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;
import com.example.android.commitcontent.ime.dict.comparators.HanZiComparator;
import com.example.android.commitcontent.ime.dict.libs.HanZiDict;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 汉字字典工具类
 */
public class HanZiDictHelper {
    /**
     * 使用拼音串从字典中检索数据
     *
     * @param pinYinList
     * @return
     */
    public static List<HanZiCharacter> queryHanZiCharactersByPinYin(List<String> pinYinList) {
        //筛选后的 精确字表、相似字表
        List<HanZiCharacter> certainlyHanZiList = new ArrayList<>();
        List<HanZiCharacter> similarHanZiList = new ArrayList<>();
        //筛选后的 精确词表、相似词表
        List<HanZiCharacter> certainlyHanZiWordList = new ArrayList<>();
        List<HanZiCharacter> similarHanZiWordList = new ArrayList<>();

        //---------从数据库检索词组----------------
        //拼音串长度大于1，从数据库中检索词组
        if (pinYinList.size() > 1) {
            //全拼组合 如 "shang,hai"
            StringBuilder wordsPinYinBuilder = new StringBuilder();
            //简拼组合 如 "s,h"
            StringBuilder wordsPinYinSimplifiedBuilder = new StringBuilder();
            //取得全/简拼组合字符串
            for (int i = 0; i < pinYinList.size(); i++) {
                String p = pinYinList.get(i);
                if (TextUtils.isEmpty(p)) continue;
                wordsPinYinBuilder.append(p);
                wordsPinYinSimplifiedBuilder.append(p.charAt(0));
                if (i < pinYinList.size() - 1) {
                    wordsPinYinBuilder.append(",");
                    wordsPinYinSimplifiedBuilder.append(",");
                }
            }
            LogHelper.e("query words " + wordsPinYinBuilder.toString() + "  " + wordsPinYinSimplifiedBuilder.toString());
            //从数据具体搜索
            certainlyHanZiWordList.addAll(HanZiStatisticsDataBaseHelper.intance(null).queryWordListByPinyin(wordsPinYinBuilder.toString()));
            //如果精确匹配没找到，那就相似匹配
            if (certainlyHanZiWordList.size() == 0)
                similarHanZiWordList.addAll(HanZiStatisticsDataBaseHelper.intance(null).queryWordListByPinyinSimplified(wordsPinYinSimplifiedBuilder.toString()));
        } else if (pinYinList.size() > 0) {
            //如果输入没有分词 如 上海 -> shang,hai-> s,h -> sh，将其拆分进行数据库模糊搜索
            String py = pinYinList.get(0);
            String p = "";
            for (int i = 0; i < py.length(); i++) {
                p += py.charAt(i);
                if (i < py.length() - 1)
                    p += ",";
            }
            similarHanZiWordList.addAll(HanZiStatisticsDataBaseHelper.intance(null).queryWordListByPinyinSimplified(p));
        }
        //对词组进行排序、合并
        Collections.sort(certainlyHanZiWordList, HanZiComparator.newInstance());
        Collections.sort(similarHanZiWordList, HanZiComparator.newInstance());
        certainlyHanZiList.addAll(certainlyHanZiWordList);
        certainlyHanZiList.addAll(similarHanZiWordList);

        //-----------根据输入的首个拼音进行字库检索字---------------
        //限制检索结果字数
        int certainlyHanZiMaxSize = 80;
        int similarHanZiListMaxSize = 10;
        String pinYin = pinYinList.get(0).toLowerCase();
        char ch = pinYin.charAt(0);
        //range a-z;
        if (ch >= 97 && ch <= 122) {
            int index = ch - 97;
            //从字库中检索数据
            List<HanZiCharacter> charAreaList = HanZiDict.ALL_LIST.get(index);
            List<HanZiCharacter> haZiByShengMu = HanZiStatisticsDataBaseHelper.intance(null).findHaZiByShengMu(String.valueOf(ch));
            for (int i = 0; i < charAreaList.size(); i++) {
                HanZiCharacter character = charAreaList.get(i);
                //拼音完全相同
                if (certainlyHanZiList.size() <= certainlyHanZiMaxSize && character.pinyin.equals(pinYin)) {
                    //从数据库获取字频
//                    character.repeatCount = HanZiStatisticsDataBaseHelper.intance(null).getRepeatCount(character.hanzi);
                    Iterator<HanZiCharacter> iterator = haZiByShengMu.iterator();
                    while (iterator.hasNext()) {
                        HanZiCharacter next = iterator.next();
                        if (next.hanzi.equals(character.hanzi)) {
                            character.repeatCount = next.repeatCount;
                            iterator.remove();
                        }
                    }
                    certainlyHanZiList.add(character);
                } else if (similarHanZiList.size() <= similarHanZiListMaxSize && character.pinyin.startsWith(pinYin)) {  //拼音相似
                    similarHanZiList.add(character);
                }
            }
            //按照字频(优先)&笔画数排序
            Collections.sort(certainlyHanZiList, HanZiComparator.newInstance());
            Collections.sort(similarHanZiList, HanZiComparator.newInstance());
            certainlyHanZiList.addAll(similarHanZiList);
        }
        return certainlyHanZiList;
    }

    public static void addHanZiToMemory(List<HanZiCharacter> hanZiCharacterList) {
        for (int i = 0; i < hanZiCharacterList.size(); i++) {
            HanZiCharacter hanZiCharacter = hanZiCharacterList.get(i);
            if (TextUtils.isEmpty(hanZiCharacter.shengmu)) continue;
            char ch = hanZiCharacter.shengmu.charAt(0);
            //range a-z;
            if (ch >= 97 && ch <= 122) {
                int index = ch - 97;
                boolean isNeedAdd = true;
                List<HanZiCharacter> charAreaList = HanZiDict.ALL_LIST.get(index);
                for (int j = 0; j < charAreaList.size(); j++) {
                    HanZiCharacter character = charAreaList.get(j);
                    if ((!TextUtils.isEmpty(hanZiCharacter.hanzi)) && (!TextUtils.isEmpty(character.hanzi)) && (!TextUtils.isEmpty(hanZiCharacter.pinyin)) && (!TextUtils.isEmpty(character.pinyin)))
                        if (hanZiCharacter.hanzi.equals(character.hanzi) && hanZiCharacter.pinyin.equals(character.pinyin))
                            isNeedAdd = false;
                }
                if (isNeedAdd)
                    charAreaList.add(hanZiCharacter);
            }
        }
    }


    public static void loadDatabaseHanZiToMemory(Context context){
        addHanZiToMemory(HanZiStatisticsDataBaseHelper.intance(context).getSavedHanZi());
    }
}
